package com.ruitu.mall_98_1.product.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.dialog.AlertDialogFragment;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.P_Global;
import com.ruitu.mall_98_1.mvp.contract.ProductDetailContract;
import com.ruitu.mall_98_1.mvp.model.ProductDetailModelImpl;
import com.ruitu.mall_98_1.mvp.presenter.ProductDetailPresenterImpl;
import com.ruitu.mall_98_1.product.adapter.SpecApter;
import com.ruitu.mall_98_1.product.fragment.EvaluateFragment;
import com.ruitu.mall_98_1.product.fragment.ProductFragment;
import com.ruitu.mall_98_1.product.support.AlertUtil;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.BuyNow;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.TextWatcherImpl;
import com.ruitu.router_module.bean.mine.Coupon;
import com.ruitu.router_module.bean.product.Company;
import com.ruitu.router_module.bean.product.ProDetail;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.bean.product.Spec;
import com.ruitu.router_module.bean.product.SpecInfo;
import com.ruitu.router_module.share.ShareUtil;
import com.ruitu.router_module.share.uitool.ShareBoard;
import com.ruitu.router_module.share.uitool.ShareBoardlistener;
import com.ruitu.router_module.share.uitool.SnsPlatform;
import com.ruitu.router_module.utils.GlideUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

public class ProductDetailActivity extends MyBaseActivity<ProductDetailPresenterImpl, ProductDetailModelImpl>
        implements ProductDetailContract.View {
    private FrameLayout fl_icon;
    private ViewPager vp;
    private View divider0, divider1, divider2;//三段分割线
    private TextView tv_product, tv_detail, tv_evaluate;
    private RelativeLayout rl_product, rl_evaluate, rl_detail;//title 商品 评价 详情
    private TextView tv_add_cart, tv_buy;//,加入购物车,立即购买
    private RelativeLayout rl_share;//分享
    private LinearLayout ll_1, ll_2, ll_3;//在线客服,收藏,店铺

    private List<View> dividerList;
    private List<TextView> titleList;

    private AlertDialog alertDialog;

    private Product p;//商品列表传过来的商品对象
    private ProDetail proDetail;//需要请求的商品详情对象
    private List<Spec> allKinds;//所有的规格和值
    private String allKindsJson = "";
    private List<Sku> skuList;//套餐形式的规格
    //    private String currSkuId = "";//当前选择的套餐的skuId
    private Sku currSku;//当前选择的套餐
    private int stock = 0;//商品库存

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 18110951) {//套餐选择完成
            currSku = (Sku) e.getEventObj();
            if (null != currSku) {
                try {
                    stock = Integer.parseInt(currSku.getModelStock());//当前套餐的库存
                } catch (Exception e1) {
                    stock = 0;
                }
                tv_price.setText("￥" + currSku.getModelPrice());
                tv_stock.setText("库存:" + currSku.getModelStock());
                if (TextUtils.equals("1", p.getShoppingGroupStatus())) {//拼团
                    if (currSku.getCollagePrice() <= 0) {
                        tv_cart_group.setText("拼团￥" + p.getCollagePrice());
                    } else {
                        tv_cart_group.setText("拼团￥" + currSku.getCollagePrice());
                    }
                }
            } else {
                try {//库存
                    stock = Integer.parseInt(p.getGoodStock());
                } catch (Exception e2) {
                    stock = 0;
                }
                tv_price.setText("￥" + p.getGoodMarket());
                tv_stock.setText("库存:" + stock);
                if (TextUtils.equals("1", p.getShoppingGroupStatus())) {//拼团
                    tv_cart_group.setText("拼团￥" + p.getCollagePrice());
                }
            }
        }
        if (e.getEventCode() == 18111951) {//选择的套餐的字符串结果
            tv_0.setText("已选:    " + (String) e.getEventObj());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        disableSlideBack();
        fl_icon = findViewById(R.id.fl_icon);
        vp = findViewById(R.id.vp);
        divider0 = findViewById(R.id.divider0);
        divider1 = findViewById(R.id.divider1);
        divider2 = findViewById(R.id.divider2);
        tv_product = findViewById(R.id.tv_product);
        tv_detail = findViewById(R.id.tv_detail);
        tv_evaluate = findViewById(R.id.tv_evaluate);
        rl_product = findViewById(R.id.rl_product);
        rl_evaluate = findViewById(R.id.rl_evaluate);
        rl_detail = findViewById(R.id.rl_detail);
        tv_add_cart = findViewById(R.id.tv_add_cart);
        tv_buy = findViewById(R.id.tv_buy);
        rl_share = findViewById(R.id.rl_share);
        ll_1 = findViewById(R.id.ll_1);
        ll_2 = findViewById(R.id.ll_2);
        ll_3 = findViewById(R.id.ll_3);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            p = (Product) bundle.getSerializable("product");
        }

        tv_product.setSelected(true);
        dividerList = Arrays.asList(divider0, divider1, divider2);
        titleList = Arrays.asList(tv_product, tv_evaluate, tv_detail);

        vp.setOffscreenPageLimit(99);
        vp.setAdapter(new VpAdapter(getSupportFragmentManager()));

        setListeners();
        Arad.bus.register(this);
        alertDialog = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        showProgress();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.reqProSpec(p.getGoodId());//请求规格型号
                if (CommonUtils.isLogin()) {
                    mPresenter.reqProDetail(p.getGoodId(), AppHolder.instance().getUser().getAccountId());
                } else {
                    mPresenter.reqProDetail(p.getGoodId(), "");
                }
            }
        }, 100);
    }

    private void setListeners() {
        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                setTxtIndicator(dividerList.get(position), titleList.get(position));
            }
        });
        fl_icon.setOnClickListener(this);
        rl_product.setOnClickListener(this);
        rl_evaluate.setOnClickListener(this);
        rl_detail.setOnClickListener(this);
        tv_buy.setOnClickListener(this);
        rl_share.setOnClickListener(this);
        ll_1.setOnClickListener(this);
        ll_2.setOnClickListener(this);
        ll_3.setOnClickListener(this);
        tv_add_cart.setOnClickListener(this);//加入购物车/拼团
    }

    private boolean isAddToCart = false;//弹窗的时候是加入购物车还是立即购买

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_buy) {
            showDialog();
        }
        if (v == tv_add_cart) {
            showDialog();
        }
        if (v == fl_icon) {
            UIUtils.hideInput(this, vp.getWindowToken());
            finish();
        }
        if (v == rl_product) {
            vp.setCurrentItem(0, true);
            if (null != proDetail1Listener) {
                proDetail1Listener.onProClick();
            }
            setTxtIndicator(divider0, titleList.get(0));
        }
        if (v == rl_evaluate) {
            vp.setCurrentItem(1, true);
        }
        if (v == rl_detail) {
            if (vp.getCurrentItem() != 0) {
                vp.setCurrentItem(0, true);
            }
            if (null != proDetail1Listener) {
                proDetail1Listener.onDetailClick();
            }
            setTxtIndicator(divider2, titleList.get(2));
        }
        if (v == ll_1) {//客服
            if (CommonUtils.isLoginToActivity(this)) {//先判断有没有登录
                if (null == proDetail || null == proDetail.getCompany()) {
                    ToastUtils.showShortSafe("正在获取客服信息,请稍后重试");
                    return;
                }
                //说明融云连接成功
                if (RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
                    Company com = proDetail.getCompany();
                    P_Global.P = p;
                    P_Global.T_ID = com.getAccountId();
                    RongIM.getInstance().startPrivateChat(this, com.getAccountId(), com.getName());
                } else {
                    ToastUtils.showShortSafe("客服连接中,请稍后重试");
                    Arad.bus.post(new EventModel(18080251));//提示主页面请求融云token并连接
                }
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == ll_2) {//收藏
            if (CommonUtils.isLoginToActivity(this)) {
                if (null == proDetail || null == p) {
                    ToastUtils.showShort("商品信息加载中,请稍候");
                    return;
                }
                if (null == p.getCollection()) {//说明没有收藏
                    hideProgress();
                    showProgressWithText(true, "正在收藏...");
                    mPresenter.reqcollect(AppHolder.instance().getUser().getAccountId(), "1", p.getGoodId());
                } else {//说明已经收藏了
                    hideProgress();
                    showProgressWithText(true, "正在取消...");
                    mPresenter.reqcollectCancel(AppHolder.instance().getUser().getAccountId(), "1", p.getCollection().getId());
                }
            } else {
                ToastUtils.showShort("请先登录");
            }
        }
        if (v == ll_3) {//店铺
            if (null == proDetail || null == proDetail.getCompany()) {
                ToastUtils.showShort("数据加载中,请稍候再试");
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("companyId", proDetail.getCompany().getId());
                startActivity(ShopDetailActivity.class, bundle);
            }
        }
        if (v == rl_share) {
            if (CommonUtils.isLoginToActivity(this)) {
                showShare();
            }
        }
    }

    private ShareBoard mShareBoard;//分享面板
    private boolean isShare = false;//是否打开了分享

    private void showShare() {
        if (null == proDetail || TextUtils.isEmpty(p.getGoodContent())) {
            ToastUtils.showShortSafe("商品信息加载中,请稍后再试");
            return;
        }

        mShareBoard = ShareUtil.getShareBoard(this);
        mShareBoard.setShareboardclickCallback(new ShareBoardlistener() {
            @Override
            public void onclick(SnsPlatform snsPlatform, String platform) {
                hideProgress();
                showProgressWithText(true, "打开分享...");
                isShare = true;
                String shareTxt = p.getGoodName();
//                String shareTitle = System.currentTimeMillis() % 2 == 0 ?
//                        "我在九八商城发现一件不错的商品，快点看看吧！" :
//                        "千挑万选，九八商城这件商品真的物美价廉，快来围观！";
                String shareTitle = "我在同城超市发现一件不错的厂家直销商品，快来看看吧！";
                if (!TextUtils.isEmpty(shareTxt)) {
                    if (shareTxt.length() >= 40) {//超过40个字,qq分享错误,
                        shareTxt = shareTxt.substring(0, 39);
                    }
                } else {
                    shareTxt = "同城超市商品";
                }
                ShareParams params = ShareUtil.getShareParams(shareTitle, shareTxt,
                        "https://www.jbshch.com/web/goodDetails/fenxiang?id=" + p.getGoodId() +"&"+ "inviteAccountId=" + AppHolder.instance().getUser().getAccountId());
                Logg.i(params.getUrl());
                JShareInterface.share(platform, params, new PlatActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享成功");
                        isShare = false;
                    }

                    @Override
                    public void onError(Platform platform, int i, int i1, Throwable throwable) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享错误");
                        Logg.i("throwable = " + throwable.toString() + Config.BASE_URL + p.getGoodContent());
                        isShare = false;
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        hideProgress();
                        ToastUtils.showShortSafe("分享取消");
                        isShare = false;
                    }
                });
            }
        });
        try {
            mShareBoard.show();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShortSafe("发生了一些错误,请稍后重试");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isShare) {
            hideProgress();
            isShare = false;
        }
    }

    private void setTxtIndicator(View divider, TextView tv_ti2tle) {//设置指示器
        for (View v : dividerList) {
            if (v == divider) {
                v.setVisibility(View.VISIBLE);
            } else {
                v.setVisibility(View.INVISIBLE);
            }
        }

        for (TextView tv : titleList) {
            if (tv == tv_title) {
                tv.setSelected(true);
            } else {
                tv.setSelected(false);
            }
        }
    }

    private void setProNum(int num, TextView tv) {//设置商品数量
        tv.setText(num + "");
    }

    private View alert_view;//对话框的布局
    private TextView tv_0;//已选的规格
    private int proNum = 1;
    private TextView tv_price;//选择完成套餐的价格
    private TextView tv_stock;//选择完成套餐的库存
    private TextView tv_cart_group;//加入购物车/拼团购买

    public void showDialog() {
        //商品详情为空,规格未请求完成
        if (null == proDetail || null == proDetail.getGoods() || !isReqModelOk) {
            ToastUtils.showShort("商品信息加载中,请稍候");
            return;
        }
        if (CommonUtils.isLogin()) {
            if (TextUtils.equals(AppHolder.instance().getUser().getAccountId()
                    , proDetail.getCompany().getAccountId())) {
                //说明当前登录用户是卖家本人
                ToastUtils.showShort("不能购买自家商品");
                return;
            }
        }
        currSku = null;//当前选择的型号id,每次弹窗置空
        if (null == alert_view) {
        }
        alert_view = View.inflate(this, R.layout.pro_alert_buy, null);
        final EditText et_num = alert_view.findViewById(R.id.et_num);//商品数量
        et_num.setText(proNum + "");
        tv_0 = alert_view.findViewById(R.id.tv_0);//已选:
        tv_price = alert_view.findViewById(R.id.tv_price);//商品价格
        tv_price.setText("￥" + p.getGoodMarket());
        tv_stock = alert_view.findViewById(R.id.tv_stock);//商品名称
        tv_stock.setText("库存:" + p.getGoodStock());
        TextView tv_pro_no = alert_view.findViewById(R.id.tv_pro_no);
        tv_pro_no.setText("商品编号:" + p.getGoodNumber());//商品编号
        TextView tv_book = alert_view.findViewById(R.id.tv_book);//预订
        ImageView iv_img = alert_view.findViewById(R.id.iv_img);//商品图片
        GlideUtil.loadImg(Config.BASE_URL + p.getImageUrl(), iv_img);//商品图片
        if (TextUtils.equals("1", p.getModelType())) {//商品类型 0 没有其他型号 1 多余型号
            tv_0.setText("已选:");//已选择的规格
        } else {
            tv_0.setText("");//不需要选规格
        }
        iv_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击商品的图片
                if (null == proDetail || isDataEmpty(proDetail.getImageList())) {
                    ToastUtils.showShort("该商品暂无大图");
                    return;
                }
                Intent intent = new Intent(ProductDetailActivity.this, PhotoCheckActivity.class);
                intent.putExtra("position", 0);
                ArrayList<String> imgPaths = new ArrayList<>();
                for (ProDetail.Img i : proDetail.getImageList()) {//封装图片路径,传到图片查看页面
                    imgPaths.add(Config.BASE_URL + i.getUrl());
                }
                intent.putExtra("list", imgPaths);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });
        et_num.addTextChangedListener(new TextWatcherImpl() {
            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(et_num.getText().toString().trim())) {
                    et_num.setText("1");
                }
                int currProNum = Integer.parseInt(et_num.getText().toString().trim());
                if (currProNum > stock) {
                    currProNum = stock;
                    ToastUtils.showShort("超出商品库存");
                    et_num.setText(currProNum + "");
                }
                proNum = currProNum;
            }
        });

        RecyclerView rcv_spec = alert_view.findViewById(R.id.rcv_spec);
        final SpecApter adapter = new SpecApter(this);
        adapter.setSkuList(skuList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rcv_spec.setLayoutManager(manager);
        rcv_spec.setAdapter(adapter);
        adapter.mDataListJson = allKindsJson;
        adapter.setDataList((List<Spec>) new Gson().fromJson(allKindsJson, new TypeToken<List<Spec>>() {
        }.getType()));

        if (TextUtils.equals("1", p.getCustomizedStatus())) {//是否预订 0 否 1 是
            tv_book.setVisibility(View.VISIBLE);
            tv_book.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (CommonUtils.isLoginToActivity(ProductDetailActivity.this)) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("product", p);
                        startActivity(BookProActivity.class, bundle);
                    } else {
                        ToastUtils.showShort("请先登录");
                    }
                }
            });
        } else {
            tv_book.setVisibility(View.GONE);
        }
        alert_view.findViewById(R.id.iv_min).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proNum = proNum <= 1 ? 1 : (proNum - 1);
                setProNum(proNum, et_num);
            }
        });
        alert_view.findViewById(R.id.iv_plus).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proNum = proNum >= 9999 ? 9999 : (proNum + 1);
                setProNum(proNum, et_num);
            }
        });
        alert_view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIUtils.hideInput(ProductDetailActivity.this, alert_view.getWindowToken());
                alertDialog.dismiss();
            }
        });

        TextView tv_ok = alert_view.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //立即购买
                if (TextUtils.equals("0", p.getStatus())) {//商品暂时下架
                    ToastUtils.showShort("商品下架,暂时不能购买");
                    return;
                }
                if (stock <= 0) {
                    ToastUtils.showShort("商品库存不足");
                    return;
                }
                if (proNum > stock) {//超出库存
                    ToastUtils.showShort("购买数量超过库存");
                    return;
                }
                try {
                    if (CommonUtils.isLoginToActivity(ProductDetailActivity.this)) {
                        if (TextUtils.equals("1", p.getModelType()) && null == currSku) {
                            ToastUtils.showShort("请选择规格型号");
                            return;
                        }
                        String currSkuId = "";
                        if (null != currSku) {
                            currSkuId = currSku.getId();
                        }
                        Bundle bundle = new Bundle();
                        BuyNow buyNow = new BuyNow();
                        buyNow.setGoodsId(p.getGoodId());
                        buyNow.setNum(proNum);
                        buyNow.setSkuId(currSkuId);
                        if (TextUtils.equals("1", p.getGoodSalesModel())) {//销售模式 1 预售 2 现货
                            buyNow.setStatus("1");//0:立即购买 1:预售 3:团购
                        } else {
                            buyNow.setStatus("0");//0:立即购买 1:预售 3:团购
                        }
                        bundle.putSerializable("buyNow", buyNow);
                        A_Rutils.startActivity(ProductDetailActivity.this,
                                "com.ruitu.mall_98_2.order.ByNowFillInOrderActivity", bundle);
                    } else {
                        ToastUtils.showShort("请先登录");
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                alertDialog.dismiss();
            }
        });

        tv_cart_group = alert_view.findViewById(R.id.tv_cart_group);
        if (TextUtils.equals("1", p.getGoodSalesModel())) {//销售模式 1 预售 2 现货
            tv_ok.setText("确定");
            tv_cart_group.setVisibility(View.GONE);
        } else {//现货
            if (TextUtils.equals("0", p.getStatus())) {//商品暂时下架
                ToastUtils.showShort("商品下架,暂时不能购买");
                return;
            }
            if (stock <= 0) {
                ToastUtils.showShort("商品库存不足");
                return;
            }
            if (proNum > stock) {//超出库存
                ToastUtils.showShort("购买数量超过库存");
                return;
            }
            if (TextUtils.equals("1", p.getShoppingGroupStatus())) {//是否设置团购 0 否 1 是
                tv_cart_group.setText("拼团￥" + p.getCollagePrice());
            } else {
                tv_cart_group.setText("加入购物车");
            }
            tv_cart_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //该按钮是加入购物车或者拼团
                    if (CommonUtils.isLoginToActivity(ProductDetailActivity.this)) {
                        if (TextUtils.equals("1", p.getModelType()) && null == currSku) {
                            ToastUtils.showShort("请选择规格型号");
                            return;
                        }
                        String currSkuId = "";
                        if (null != currSku) {
                            currSkuId = currSku.getId();
                        }
                        if (TextUtils.equals("1", p.getShoppingGroupStatus())) {//1 团购 0 普通商品
                            try {//立即购买
                                Bundle bundle = new Bundle();
                                BuyNow buyNow = new BuyNow();
                                buyNow.setGoodsId(p.getGoodId());
                                buyNow.setNum(proNum);
                                buyNow.setSkuId(currSkuId);
                                buyNow.setStatus("3");//0:立即购买 1:预售 3:团购
                                bundle.putSerializable("buyNow", buyNow);
                                A_Rutils.startActivity(ProductDetailActivity.this,
                                        "com.ruitu.mall_98_2.order.ByNowFillInOrderActivity", bundle);
                            } catch (Exception e) {
                            }
                        } else {//加入购物车
                            hideProgress();
                            showProgressWithText(true, "正在添加...");
                            mPresenter.addToCart(p.getGoodId(), AppHolder.instance().getUser().getAccountId(), proNum, currSkuId);
                        }
                    } else {
                        ToastUtils.showShort("请先登录");
                    }
                    alertDialog.dismiss();
                }
            });
        }
        alertDialog.show();
        AlertUtil.setAlertBottomInStyle(alertDialog.getWindow(), alert_view, this);

        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        alertDialog.setCanceledOnTouchOutside(false);
    }

    //请求评论列表
    public void reqEvaluateList() {
        if (null != onProEvaluateListener) {
            onProEvaluateListener.onReqEvalute(proDetail);
        }
    }

    //显示商品介绍页面
    public void setAsProIntro(int index) {
        if (index == 0) {
            setTxtIndicator(divider0, titleList.get(0));
        } else if (index == 2) {
            setTxtIndicator(divider2, titleList.get(2));
        } else if (index == 1) {
            vp.setCurrentItem(1, true);
        }
    }

    //领取优惠券
    public void reqGetCoupon(Coupon coupon) {
        if (CommonUtils.isLoginToActivity(this)) {
            hideProgress();
            showProgressWithText(true, "领取中...");
            mPresenter.reqGetCoupon(AppHolder.instance().getUser().getAccountId(), coupon.getId());
        } else {
            ToastUtils.showShort("请先登录");
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            Arad.bus.post(new EventModel(18102951));
        }
    }

    @Override
    public void onReqComplete(boolean isSuc, int type, Object data) {
        if (type == 1) {//商品详情请求成功
            if (!isSuc) {//请求商品详情失败了
                try {
                    AlertDialogFragment alert = UIUtils.showAlertDialog(getSupportFragmentManager()
                            , "温馨提示", "咦？好像发生了一些异常，请稍后重试。"
                            , "重试", "返回"
                            , new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mPresenter.reqProSpec(p.getGoodId());//请求规格型号

                                    hideProgress();
                                    showProgress();
                                    if (CommonUtils.isLogin()) {
                                        mPresenter.reqProDetail(p.getGoodId(), AppHolder.instance().getUser().getAccountId());
                                    } else {
                                        mPresenter.reqProDetail(p.getGoodId(), "");
                                    }
                                }
                            }, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                    alert.setCancelable(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            proDetail = (ProDetail) data;
            p = proDetail.getGoods();
            setProInfo();//设置商品信息(子页面处理)

            if (TextUtils.equals("1", p.getShoppingGroupStatus())) {//是否设置团购 0 否 1 是
                tv_add_cart.setText("拼团￥" + p.getCollagePrice());
            } else {
                tv_add_cart.setText("加入购物车");
            }
            if (TextUtils.equals("1", p.getGoodSalesModel())) {//销售模式 1 预售 2 现货
                tv_add_cart.setVisibility(View.GONE);
                tv_buy.setText("商品预售");
            }
            if (TextUtils.equals("0", p.getStatus())) {//0 下线 1 在售
                tv_add_cart.setVisibility(View.GONE);
                tv_buy.setText("商品已下架");
                tv_buy.setBackgroundResource(R.color.pro_xiajia_gray);
                tv_buy.setTextColor(getResources().getColor(R.color.text_dark_gray));
            }
            if (null != p.getCollection()) {//说明已经收藏了
                ll_2.setSelected(true);
            } else {
                ll_2.setSelected(false);
            }

            reqEvaluateList();//通知评价页面请求评价列表

            try {//库存
                stock = Integer.parseInt(p.getGoodStock());
            } catch (Exception e) {
                stock = 0;
            }
        } else if (type == 2) {//规格请求成功
            SpecInfo specInfo = (SpecInfo) data;
            skuList = specInfo.getSkuList();
            allKinds = specInfo.getAllKinds();
            try {
                Logg.i("spec...skuList.size = " + skuList.size() + "...allKinds.0.getGoodsFeatureVals = " + allKinds.get(0).getGoodsFeatureVals().size());
            } catch (Exception e) {
                e.printStackTrace();
            }
            allKindsJson = new Gson().toJson(allKinds);//数据转成json字符串
            isReqModelOk = true;
        } else if (type == 3) {//收藏
            ll_2.setSelected(true);
            //能收藏成功,说明肯定登录了
            mPresenter.reqProDetail(p.getGoodId(), AppHolder.instance().getUser().getAccountId());
        } else if (type == 4) {//取消收藏
            ll_2.setSelected(false);
            p.setCollection(null);
        }
    }

    private boolean isReqModelOk = false;//规格是否请求完成(请求完成才能选择购买或者加入购物车)

    //设置商品信息
    private void setProInfo() {
        if (null != proDetail && null != proDetail.getGoods()) {
            if (null != proDetail1Listener) {
                proDetail1Listener.onGetProInfo(proDetail);//请求规格
            }
        }
    }

    private class VpAdapter extends FragmentPagerAdapter {

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return ProductFragment.newInstance();
            } else if (position == 1) {
                return EvaluateFragment.newInstance();
            }
            return ProductFragment.newInstance();
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

    private OnProEvaluateListener onProEvaluateListener;//商品评价用到

    public void setOnProEvaluateListener(OnProEvaluateListener onProEvaluateListener) {
        this.onProEvaluateListener = onProEvaluateListener;
    }

    public interface OnProEvaluateListener {
        void onReqEvalute(ProDetail proDetail);//此时请求商品详情
    }

    ProDetail1Listener proDetail1Listener;//商品介绍页面用到

    public void setProDetail1Listener(ProDetail1Listener proDetail1Listener) {
        this.proDetail1Listener = proDetail1Listener;
    }

    public interface ProDetail1Listener {

        void onDetailClick();//外层点击详情

        void onProClick();//外层点击商品介绍

        void onGetProInfo(ProDetail proDetail);//商品信息请求成功时执行
    }
}
